package com.eurasia.assignment.domain;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Component
@Slf4j
public class FileStorage {

    @Value("${file.upload-dir:./uploads}")
    private String uploadDir;

    /**
     * 存储文件到文件系统
     * 
     * @param file 上传的文件
     * @param fileName 存储的文件名
     * @return 文件的存储路径
     * @throws IOException 如果文件存储失败
     */
    public String storeFile(MultipartFile file, String fileName) throws IOException {
        try {
            Path uploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();
            
            // 创建上传目录（如果不存在）
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 目标文件路径
            Path targetLocation = uploadPath.resolve(fileName);
            
            // 复制文件到目标路径，如果已存在则替换
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            
            return uploadPath.toString() + "/" + fileName;
        } catch (IOException ex) {
            log.error("无法存储文件 {}. 错误: {}", fileName, ex.getMessage());
            throw new IOException("无法存储文件 " + fileName, ex);
        }
    }
    
    /**
     * 将文件加载为资源
     * 
     * @param fileName 存储的文件名
     * @return 文件资源
     * @throws MalformedURLException 如果URL格式错误
     */
    public Resource loadFileAsResource(String fileName) throws MalformedURLException {
        try {
            Path uploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();
            Path filePath = uploadPath.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            
            if (resource.exists()) {
                return resource;
            } else {
                throw new RuntimeException("文件未找到 " + fileName);
            }
        } catch (MalformedURLException ex) {
            log.error("无法加载文件 {}. 错误: {}", fileName, ex.getMessage());
            throw new MalformedURLException("无法加载文件 " + fileName);
        }
    }
} 